package com.message.api.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.base.helper.StringUtils;
import com.message.api.user.dao.AcUserMapper;
import com.message.api.user.entity.AcUser;
import com.message.api.user.service.AcUserService;
import com.message.api.user.vo.AcUserVo;
import com.message.api.user.vo.EnSetPwdVo;
import com.message.api.user.vo.RegisterExamineeVo;
import com.message.api.user.vo.RegisterStudentVo;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mzl
 * @since 2020-07-09
 */
@Service
public class AcUserServiceImpl extends ServiceImpl<AcUserMapper, AcUser> implements AcUserService {

    @Override
    public Page<AcUserVo> findByPage(Page<AcUserVo> page, AcUserVo example) {

        /** 不进行 count sql 优化，解决 MP 无法自动优化 SQL 问题 */
        page.setOptimizeCountSql(false);
        return page.setRecords(baseMapper.findByExample(buildWrapper(example), page));
    }

    @Override
    public List<AcUserVo> findByExample(AcUserVo example) {
        return baseMapper.findByExample(buildWrapper(example));
    }

    @Override
    public List<AcUserVo> findByGroupid(Integer groupid) {
        QueryWrapper<AcUserVo> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(AcUserVo::getAcgroup, groupid).eq(AcUserVo::getState, "1");
        return this.baseMapper.findByExample(wrapper);
    }

    private QueryWrapper<AcUserVo> buildWrapper(AcUserVo example) {
        QueryWrapper<AcUserVo> wrapper = new QueryWrapper<AcUserVo>();

        /** 条件查询 */
        Integer acgroup         = example.getAcgroup();
        String  acgroupName     = example.getAcgroupName();
        Integer usertype        = example.getUsertype();
        String  usertypeName    = example.getUsertypeName();
        String  username        = example.getUsername();
        String  enable          = example.getEnable();

        wrapper.lambda()
                .eq(null != acgroup, AcUserVo::getAcgroup, acgroup)
                .eq(null != usertype, AcUserVo::getUsertype, usertype)
                .like(StringUtils.isNotEmpty(username), AcUserVo::getUsername, username)
                .eq(StringUtils.isNotEmpty(enable), AcUserVo::getEnable, enable)
                .eq(AcUserVo::getState, "1")
                .orderByDesc(AcUserVo::getId);

        /** 外键不支持lambda */
        wrapper.like(StringUtils.isNotEmpty(acgroupName), "acgroup_name", acgroupName)
                .like(StringUtils.isNotEmpty(usertypeName), "usertype_name", usertypeName);

        //搜索用户姓名
        String realname = example.getRealname();
        if (StringUtils.isNotEmpty(realname)) {
            wrapper.and(w -> w.like("realname", realname));
        }
        return wrapper;
    }

    @Override
    public AcUser findByUsername(String username) {
        return this.baseMapper.findByUsername(username);
    }

    @Override
    public AcUser setEnable(Integer id, String enable) {
        AcUser acUser = this.getById(id);
        if (null == acUser || "0".equals(acUser.getState())) {
            throw new RuntimeException("没有找到id对应对象");
        }
        if (enable.equals(acUser.getEnable())) {
            throw new RuntimeException("该用户已经处于该状态");
        }
        acUser.setEnable(enable);
        this.updateById(acUser);
        return acUser;
    }

    @Override
    public AcUser registerExamineeUser(RegisterExamineeVo examinee) {
        AcUser acUser = new AcUser();
        acUser.setUsername(examinee.getUsername());
        acUser.setRealname(examinee.getRealname());
        acUser.setPassword(examinee.getIdentitynum().substring(examinee.getIdentitynum().length() - 6));
        acUser.setAcgroup(examinee.getAcgroup());
        acUser.setUsertype(examinee.getUsertype());
        acUser.setEnable("1");
        acUser.setCreatetime(new Date());
        acUser.setPwdupdatetime(new Date());
        acUser.setState("1");
        if (this.save(acUser)) {
            return this.findByUsername(examinee.getUsername());
        } else {
            return null;
        }
    }

    @Override
    public AcUser registerStudentUser(RegisterStudentVo student) {
        AcUser acUser = new AcUser();
        acUser.setUsername(student.getUsername());
        acUser.setRealname(student.getName());
        acUser.setPassword(student.getExamineenum().substring(student.getExamineenum().length() - 6));
        acUser.setAcgroup(student.getAcgroup());
        acUser.setUsertype(student.getUsertype());
        acUser.setEnable("1");
        acUser.setCreatetime(new Date());
        acUser.setPwdupdatetime(new Date());
        acUser.setState("1");
        if (this.save(acUser)) {
            return this.findByUsername(student.getUsername());
        } else {
            return null;
        }
    }

    @Override
    public AcUser updateUserRealname(Integer id, String realname) {
        AcUser acUser = this.getById(id);
        if (null != acUser && "1".equals(acUser.getState())) {
            acUser.setRealname(realname);
            this.updateById(acUser);
            return acUser;
        }
        return null;
    }

    @Override
    public AcUser setPwd(EnSetPwdVo setPwd) {
        AcUser acUser = this.baseMapper.findByResettoken(setPwd.getToken());
        if (null == acUser || "0".equals(acUser.getState())) {
            throw new RuntimeException("没有找到对应考生");
        }
        acUser.setPassword(setPwd.getPwd());
        super.updateById(acUser);
        return acUser;
    }

    @Override
    public List<AcUser> deleteByUserIds(List<Integer> userIds) {
        QueryWrapper<AcUser> wrapper = new QueryWrapper<>();
        wrapper.lambda().in(AcUser::getId, userIds);
        List<AcUser> list = super.list(wrapper);
        this.removeByIds(userIds);
        return list;
    }

    @Override
    public List<AcUser> selectByAcGroupAndDepartmentId(Integer acGroup, Integer departmentId) {
        return this.baseMapper.selectByAcGroupAndDepartmentId(acGroup,departmentId);
    }

    @Override
    public AcUser findByTeacherNumber(String teacherNumber) {
        return this.baseMapper.findByTeacherNumber(teacherNumber);
    }

}
